package com.heima.se.method;

/**
 * @author jack
 * @data 2024 14:13
 */

public class Demo2 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33, 44, 55, 66};
        //需求： 设计一个算法，查找55在数组中的索引位置
        int index = binarySearch(arr,88);
        System.out.println("index = " + index);
    }

    //算法：二分查找
    private static int binarySearch(int[] arr, int num) {
        int min = 0;
        int max = arr.length -1;

        while (min <= max) {
            int mid = (min + max) / 2;
            if (arr[mid] > num){
                max = mid -1;
            }else if (arr[mid] < num){
                min = mid + 1;
            }else{
                return mid;
            }
        }
        return  -1;
    }
}
